#include "calServer.hpp"
#include <memory>

using namespace Server;
using namespace std;

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage:\n\t" << proc << " local_port" << std::endl
              << std::endl;
}

bool cal(const Request &req, Response &resp)
{
    // 只进行逻辑处理而不考虑其他的任何读写等——解耦

    // 走到这，请求已经是结构化的了
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if(req._y == 0) resp._exitcode = DIV_ZERO; 
        else resp._result = req._x / req._y;
        break;
    case '%':
        if(req._y == 0) resp._exitcode = MOD_ZERO; 
        else resp._result = req._x % req._y;
        break;
    default:
        resp._exitcode = OP_ERROR;
        break;
    }

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    // 1.
    uint16_t port = atoi(argv[1]);
    unique_ptr<calServer> tsr(new calServer(port));

    // 2.
    tsr->init();

    // 3.
    tsr->start(cal);

    return 0;
}